﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using Microsoft.WindowsAPICodePack.Sensors;
using System.ComponentModel;

namespace SensorHOL
{
    public class SensorHelper<SensorType, SensorPropertyType> : INotifyPropertyChanged
        where SensorType : Sensor
        where SensorPropertyType : class
    {
        private SensorPropertyType _value;
        private SensorType _sensor;
        private Guid _sensorGUID;

        public SensorHelper()
        { }

        public void Initialize()
        {
            SensorList<SensorType> list = SensorManager.GetSensorsByTypeId<SensorType>();

            if (list != null)
            {
                var permReqSensorList = new SensorList<Sensor>();
                foreach (var sensor in list)
                {
                    permReqSensorList.Add(sensor);
                }

                SensorManager.RequestPermission(IntPtr.Zero, true, permReqSensorList);

                foreach (var sensor in list)
                {
                    if (HandleNewSensor(sensor) && _sensor != null)
                        break;
                }
            }

            // subscribe to sensor added/removed event
            SensorManager.SensorsChanged += new SensorsChangedEventHandler(OnSensorsChanged);
        }

        private void OnSensorsChanged(SensorsChangedEventArgs change)
        {
            // if sensor was added
            if (change.Change == SensorAvailabilityChange.Addition && _sensor == null)
            {
                // we use the base Sensor class as the type parameter
                // because we're not sure what sensor type was attached
                Sensor sensor = SensorManager.GetSensorBySensorId<Sensor>(change.SensorId);
                // if this is the right sensro type
                if (sensor is SensorType)
                    HandleNewSensor(sensor);
            }

            if (change.Change == SensorAvailabilityChange.Removal && _sensorGUID.Equals(change.SensorId))
            {
                _sensor = null;
                _sensorGUID = Guid.Empty;
            }
        }

        private bool HandleNewSensor(Sensor sensor)
        {
            // Sensor may become Ready in the future, register for StateChanged event
            sensor.StateChanged += OnSensorStateChanged;
            if (sensor.State == SensorState.Ready)
            {
                // If sensor is already in state Ready, use it
                PrepareSensor(sensor);
                return true;
            }

            return false;
        }

        private void OnSensorStateChanged(Sensor sender, EventArgs e)
        {
            if (sender.State == SensorState.Ready)
            {
                PrepareSensor(sender);
            }
            else if (!_sensorGUID.Equals(Guid.Empty) && _sensor.SensorId.Equals(_sensorGUID))
            {
                _sensor = null;
                _sensorGUID = Guid.Empty;
                sender.DataReportChanged -= OnDataUpdated;
            }
        }

        private void PrepareSensor(Sensor sensor)
        {
            if (_sensor == null)
            {
                _sensorGUID = sensor.SensorId.Value;
                _sensor = (SensorType)sensor;
                sensor.TryUpdateData();
                sensor.DataReportChanged += OnDataUpdated;
            }
        }

        private void OnDataUpdated(Sensor sender, EventArgs e)
        {
            if (sender is AmbientLightSensor)
            {
                _value = ((AmbientLightSensor)sender).CurrentLuminousIntensity as SensorPropertyType;
            }
            else if (sender is Accelerometer3D)
            {
                _value = ((Accelerometer3D)sender).CurrentAcceleration as SensorPropertyType;
            }

            if (_value != null)
                OnPropertyChanged("Value");
        }

        public SensorPropertyType Value
        {
            get { return _value; }
        }


        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler ph = this.PropertyChanged;
            if (ph != null)
                ph(this, new PropertyChangedEventArgs(name));
        }

        #endregion
    }
}